/**
 * HTML预览组件
 * 提供安全的HTML内容预览功能，支持多种预览模式
 */

import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { 
  Eye, 
  Code, 
  Maximize2, 
  Minimize2, 
  RefreshCw, 
  ExternalLink,
  Monitor,
  Smartphone,
  Tablet
} from 'lucide-react';

/**
 * HTML预览组件
 * @param {Object} props - 组件属性
 * @param {string} props.htmlContent - HTML内容
 * @param {string} props.title - 预览标题
 * @param {boolean} props.showStats - 是否显示统计信息
 * @param {boolean} props.showControls - 是否显示控制按钮
 * @param {string} props.className - 自定义样式类名
 */
const HtmlPreview = ({
  htmlContent,
  title = "HTML预览",
  showStats = true,
  showControls = true,
  className = ""
}) => {
  const [previewMode, setPreviewMode] = useState('desktop'); // desktop, tablet, mobile
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const iframeRef = useRef(null);

  // 预览模式配置
  const previewModes = {
    desktop: { 
      icon: Monitor, 
      label: '桌面', 
      width: '100%',
      height: '500px'
    },
    tablet: { 
      icon: Tablet, 
      label: '平板', 
      width: '768px',
      height: '500px'
    },
    mobile: { 
      icon: Smartphone, 
      label: '手机', 
      width: '375px',
      height: '500px'
    }
  };

  // 处理刷新预览
  const handleRefresh = () => {
    setIsLoading(true);
    if (iframeRef.current) {
      iframeRef.current.src = iframeRef.current.src;
    }
    setTimeout(() => setIsLoading(false), 500);
  };

  // 处理全屏切换
  const handleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // 处理在新窗口打开
  const handleOpenInNewWindow = () => {
    if (htmlContent) {
      const newWindow = window.open('', '_blank');
      newWindow.document.write(htmlContent);
      newWindow.document.close();
    }
  };

  // 获取统计信息
  const getStats = () => {
    if (!htmlContent) return null;
    
    const lines = htmlContent.split('\n').length;
    const chars = htmlContent.length;
    const words = htmlContent.split(/\s+/).filter(word => word.trim()).length;
    const size = Math.round(chars / 1024 * 100) / 100;
    
    return { lines, chars, words, size };
  };

  const stats = getStats();
  const currentMode = previewModes[previewMode];

  if (!htmlContent) {
    return (
      <Card className={className}>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Eye className="size-5" />
            {title}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-muted-foreground">
            <Eye className="size-12 mx-auto mb-4 opacity-50" />
            <p>没有HTML内容可预览</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={`${className} ${isFullscreen ? 'fixed inset-4 z-50' : ''}`}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <Eye className="size-5" />
            {title}
          </CardTitle>
          
          {showControls && (
            <div className="flex items-center gap-2">
              {/* 预览模式切换 */}
              <div className="flex items-center gap-1 border rounded-md p-1">
                {Object.entries(previewModes).map(([mode, config]) => {
                  const Icon = config.icon;
                  return (
                    <Button
                      key={mode}
                      variant={previewMode === mode ? "default" : "ghost"}
                      size="sm"
                      onClick={() => setPreviewMode(mode)}
                      className="h-8 px-2"
                      title={config.label}
                    >
                      <Icon className="size-4" />
                    </Button>
                  );
                })}
              </div>

              {/* 控制按钮 */}
              <div className="flex items-center gap-1">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleRefresh}
                  disabled={isLoading}
                  title="刷新预览"
                >
                  <RefreshCw className={`size-4 ${isLoading ? 'animate-spin' : ''}`} />
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleFullscreen}
                  title={isFullscreen ? "退出全屏" : "全屏预览"}
                >
                  {isFullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleOpenInNewWindow}
                  title="在新窗口打开"
                >
                  <ExternalLink className="size-4" />
                </Button>
              </div>
            </div>
          )}
        </div>

        {/* 统计信息 */}
        {showStats && stats && (
          <div className="flex items-center gap-4 text-sm text-muted-foreground">
            <Badge variant="outline" size="sm">
              {stats.lines} 行
            </Badge>
            <Badge variant="outline" size="sm">
              {stats.chars} 字符
            </Badge>
            <Badge variant="outline" size="sm">
              {stats.words} 单词
            </Badge>
            <Badge variant="outline" size="sm">
              {stats.size} KB
            </Badge>
            <Badge variant="outline" size="sm">
              {currentMode.label}模式
            </Badge>
          </div>
        )}
      </CardHeader>

      <CardContent>
        <div className="border rounded-lg overflow-hidden">
          {/* 预览容器 */}
          <div 
            className="relative bg-gray-50"
            style={{
              width: previewMode === 'desktop' ? '100%' : currentMode.width,
              height: currentMode.height,
              margin: previewMode === 'desktop' ? '0' : '0 auto',
              maxWidth: '100%'
            }}
          >
            <iframe
              ref={iframeRef}
              srcDoc={htmlContent}
              className="w-full h-full border-0"
              title="HTML预览"
              sandbox="allow-scripts allow-same-origin allow-forms"
              style={{
                background: 'white'
              }}
              onLoad={() => setIsLoading(false)}
            />
            
            {/* 加载指示器 */}
            {isLoading && (
              <div className="absolute inset-0 bg-white bg-opacity-75 flex items-center justify-center">
                <div className="flex items-center gap-2">
                  <RefreshCw className="size-4 animate-spin" />
                  <span className="text-sm">加载中...</span>
                </div>
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default HtmlPreview;
